package com.example.second_app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

public class ProgressDialogTest extends Activity {
    private int[] data = new int[100];
    int hasData = 0;
    final int PROGRESS_DIALOG = 0x112;
    int progressStatus = 0;
    ProgressDialog pd;
    Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            // 更新进度条的进度
            if (msg.what == PROGRESS_DIALOG) {
                pd.setProgress(progressStatus);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button execBn = (Button) findViewById(R.id.button8);
        execBn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View source) {
                showDialog(PROGRESS_DIALOG);
            }
        });
    }

    @Override
    public Dialog onCreateDialog(int id, Bundle status) {
        System.out.println("------create------");
        if (id == PROGRESS_DIALOG) {
            pd = new ProgressDialog(this);
            pd.setMax(100);
            pd.setTitle("任务完成百分比");
            pd.setMessage("耗时任务的完成百分比");
            pd.setCancelable(false);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setIndeterminate(false);
        }
        return pd;
    }

    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        System.out.println("------prepare------");
        super.onPrepareDialog(id, dialog);
        if (id == PROGRESS_DIALOG) {
            pd.setProgress(0);
            new Thread(new Runnable() {
                public void run() {
                    while (progressStatus < 100) {
                        progressStatus = doWork();
                        handler.sendEmptyMessage(PROGRESS_DIALOG);
                    }
                    if (progressStatus >= 100) {
                        pd.dismiss();
                    }
                }
            }).start();
        }
    }

    public int doWork() {
        data[hasData++] = (int) (Math.random() * 100);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return hasData;
    }
}